package com.garlic.face.jlf.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.garlic.face.jlf.App;
import com.garlic.face.jlf.R;
import com.garlic.face.jlf.base.BaseActivity;
import com.garlic.face.jlf.model.BaseGoodsItem;
import com.garlic.face.jlf.presenter.ScanGoodsContract;
import com.garlic.face.jlf.presenter.ScanGoodsPresenter;
import com.garlic.face.jlf.transaction.Means;
import com.garlic.face.jlf.transaction.ServiceInterface;
import com.garlic.face.jlf.transaction.balance.LampUtil;
import com.garlic.face.jlf.transaction.balance.ReadSerialPort;
import com.garlic.face.jlf.transaction.balance.SerialPortFunction;
import com.garlic.face.jlf.transaction.balance.cclhelper.GoodsHelper;
import com.garlic.face.jlf.transaction.balance.database.GoodsWeight;
import com.garlic.face.jlf.transaction.bean.SaleFlow;
import com.garlic.face.jlf.transaction.bean.TradeHead;
import com.garlic.face.jlf.transaction.constances.JLFConstant;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.ScreenUtils;
import com.garlic.face.jlf.utils.ToastUtils;
import com.garlic.face.jlf.utils.Tools;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author wenhui02.liu
 * @date 2018/8/10.
 */

public class ScanGoodsActivity extends BaseActivity implements GoodsRecyclerViewAdapter.OnItemListener, ScanGoodsContract.View, ReadSerialPort.DataWeight {

    private String TAG = "ScanGoodsActivity";
    private ImageView mShopBrand;
    private RecyclerView mRecyclerView;
    private GoodsRecyclerViewAdapter mAdapter;
    private Dialog mItemDialog;
    private boolean mItemDialogIsShow = false;
    private TradeHead mCurrentOrder = new TradeHead();
    private TextView /*mMchCoupon, mTotalAmount,*/ mTotalCount, mPrice, mAddOneTips, mMemeberLogin;
    private ShowHandInputDialog memberLoginDialog;
    private String mCurrentBarCode = "";

    private View mCancelView, mConfirmView, mHandInputView;

    private ScanGoodsPresenter mPresenter;

    //输入对话框的三种类型：条码、优惠券、会员
    private final int IS_BARCODE = 0;
    private final int IS_COUPON = 1;
    private final int IS_MEMBER = 2;
    private final int CONFIRM_GOODS = 111;


    private static final int MSG_BARCODE = 10010;
    private BarCodeHandler mBarcodeHanler = new BarCodeHandler(this);

    private SerialPortFunction serialPortFunction;

//    private WeightDialog weightDialog;
    private WeightTipsDialog weightTipsDialog;
//    private static SuperVisorDialog superVisorDialog;
    private SuperVisorConfirmDialog supervisorLoginDialog;
    private ChangeGoodsDialog mChangeGoodsDialog;
    private String superVisor = "";//记录输入的管理员号
    private String superVisorPwd = "";//记录输入的管理员密码
    boolean blScannerEvent = false;//true-允许触发扫描事件
    boolean blScaleEvent = false; //true-允许触发电子称事件
//    private NormalDialog confirmDlg;
    private CommonDialog confirmDlg;
    private String cardNumber = "";
    private String points = "";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scan_goods_activity);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);


        mPresenter = new ScanGoodsPresenter(this);
        mPresenter.setWeightHandler(weightHandler);

        cardNumber = getIntent().getStringExtra("cardnumber");
        points = getIntent().getStringExtra("points");
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        serialPortFunction = SerialPortFunction.getInstance();
        serialPortFunction.setContext(this);
        serialPortFunction.startSerialReadEle(this);
        mPresenter.openExecutorService();
    }

    private void initData() {
//        EventBus.getDefault().register(this);
//        serialPortFunction = SerialPortFunction.getInstance();
//        serialPortFunction.setContext(this);
//        serialPortFunction.startSerialReadEle(this);
        blScaleEvent = true;

        if (getIntent() != null) {
            String bar_code = getIntent().getStringExtra("bar_code");
            if (!TextUtils.isEmpty(bar_code)) {
                mCurrentBarCode = bar_code;
                sendMsgToService(bar_code, "1");
                mCurrentBarCode = "";
            } else {
                boolean handinput = getIntent().getBooleanExtra("handinput", false);
                if (handinput) {
                    showHandInputDialog(IS_BARCODE);
                }
            }
        }
    }

    private void initView() {
        mHandInputView = findViewById(R.id.handInput);
        mCancelView = findViewById(R.id.cancel);
        mConfirmView = findViewById(R.id.confirm_pay_btn);
        mAddOneTips = findViewById(R.id.add_one_tips);
//        mAddOneTips.setVisibility(View.GONE);
        //mMchCoupon = (TextView) findViewById(R.id.mch_coupon);
        //mTotalAmount = (TextView) findViewById(R.id.total_amount);
        mTotalCount = (TextView) findViewById(R.id.total_count);
        mPrice = (TextView) findViewById(R.id.total_price);
        mMemeberLogin = findViewById(R.id.member_login);
        if (!TextUtils.isEmpty(cardNumber)) {
            mMemeberLogin.setText(String.format(getResources().getString(R.string.vip_hint),
                    cardNumber, points));
        }


        mShopBrand = (ImageView) findViewById(R.id.title_img);
        mShopBrand.setImageDrawable(this.getResources().getDrawable(R.mipmap.jlf_logo));


        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL));
        mRecyclerView.setAdapter(mAdapter);

        mCancelView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                cancelTransaction();
            }
        });
        mConfirmView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mBarcodeHanler.hasMessages(MSG_BARCODE)) {
                    ToastUtils.toastShow("处理中，请稍后", ToastUtils.SUCCESS);
                    return;
                }

                if(!mPresenter.getIsVerify() && !mPresenter.getIsCancelling()){
                    mPresenter.calcItemPriceEnd();
                }
            }
        });

        mHandInputView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showHandInputDialog(IS_BARCODE);
            }
        });
        mMemeberLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                showHandInputDialog(IS_MEMBER);
                showMemberLoginDialog();
            }
        });

    }

    private void showMemberLoginDialog() {
        memberLoginDialog = new ShowHandInputDialog(this, IS_MEMBER);
        memberLoginDialog.setCallBack(new ShowHandInputDialog.CallBack() {
            @Override
            public void close(View view) {
                memberLoginDialog.dismiss();
            }

            @Override
            public void done(String code) {
                getMemberInfo(code);
                memberLoginDialog.dismiss();
            }
        });
        memberLoginDialog.show();
    }

    private void getMemberInfo(String vipNumber) {
        showProgress();
        ServiceInterface.getInstance().getVipNumber(vipNumber);
    }


    @Override
    public void gotoMain() {
        finish();
    }

    @Override
    public void refreshVipTextView(String cardnumber, String points) {
        mMemeberLogin.setText(String.format(getResources().getString(R.string.vip_hint),
                cardnumber, points));
    }

    @Override
    public void setBlscaleEvent(boolean b) {
        blScaleEvent = b;
    }

    @Override
    public void hideSuperVisorDlg() {
        if(supervisorLoginDialog != null){
            supervisorLoginDialog.dismiss();
        }
        superVisor = "";
        superVisorPwd = "";
    }

    @Override
    public void showNormalDlog() {
        String operateId = superVisor.toString();
        /*
        confirmDlg = NormalDialog.newInstanceTwo("确认重量","确认装袋台上商品无误吗？");
        confirmDlg.setCallBackTwo(new NormalDialog.CallBackTwo() {
            @Override
            public void twoOk(View view) {

                mPresenter.processNor(operateId);
                confirmDlg.dismiss();
                Means.blApproveWeight = true;

            }

            @Override
            public void twoCancel(View view) {
                confirmDlg.dismiss();
            }
        });
        confirmDlg.show(getFragmentManager(),TAG);
        */
        confirmDlg = new CommonDialog(ScanGoodsActivity.this, "two", "确认重量","确认装袋台上商品无误吗？");
        confirmDlg.setCallBackTwo(new CommonDialog.CallBackTwo() {
            @Override
            public void twoOk(View view) {
                mPresenter.processNor(operateId);
                confirmDlg.dismiss();
                Means.blApproveWeight = true;
            }

            @Override
            public void twoCancel(View view) {
                confirmDlg.dismiss();
                Means.TotalWeight = Means.weightqty;
            }
        });
        confirmDlg.show();
    }

    @Override
    public void setSuperVisorPwd(String s) {
        superVisorPwd = s;
    }

    private void sendMsgToService(String barcode, String qty) {
        Message message = new Message();
        message.what = MSG_BARCODE;
        message.obj = new BaseGoodsItem(barcode, qty);
        mBarcodeHanler.sendMessage(message);
        LogUtils.d("send msg" + message.obj, true);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (!mItemDialogIsShow) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                LogUtils.d("getAction=" + String.valueOf(event.getAction())
                        + ";getKeyCode=" + String.valueOf(event.getKeyCode())
                        + ";getCharacters=" + event.getCharacters()
                        + ";getScanCode=" + event.getScanCode()
                        + ";getUnicodeChar=" + event.getUnicodeChar()
                        + ";getNumber=" + event.getNumber(), false);
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    if(mPresenter.getIsVerify() || mPresenter.getIsCancelling()){
                        mCurrentBarCode = "";
                        ToastUtils.toastShow("扫码过快", ToastUtils.ERROR);
                    }else {
                        sendMsgToService(mCurrentBarCode, "1");
                        mCurrentBarCode = "";
                    }
                } else if (event.getUnicodeChar() == 0) {
                } else if ((char) event.getUnicodeChar() == '#') {
                    if(mPresenter.getIsVerify() || mPresenter.getIsCancelling()){
                        mCurrentBarCode = "";
                        ToastUtils.toastShow("扫码过快", ToastUtils.ERROR);
                    }else{
                        if (mCurrentBarCode.startsWith("null")) {
                            mCurrentBarCode = mCurrentBarCode.replace("null", "");
                        }
                        sendMsgToService(mCurrentBarCode, "1");
                        mCurrentBarCode = "";
                    }
                } else {
                    mCurrentBarCode += (char) event.getUnicodeChar();
                }
            }
        } else {
            mCurrentBarCode = "";
        }
        return super.dispatchKeyEvent(event);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveResponse(JSONObject jsonObject) {
        LogUtils.d("收到service消息 " + jsonObject.toString(), true);
        mPresenter.parseResponse(jsonObject);
    }

    @Override
    protected void onPause() {
        super.onPause();
        serialPortFunction.closeEle();
        mPresenter.shutDownThread();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);

        //mBarcodeHanler.removeCallbacksAndMessages(null);
        Means.weightqty = 0;
        if(weightTipsDialog != null){
            weightTipsDialog.dismiss();
            weightTipsDialog = null;
        }
//        serialPortFunction.closeEle();
//        mPresenter.shutDownThread();

    }

    private void cancelTransaction() {
        View root = View.inflate(ScanGoodsActivity.this, R.layout.close_dialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(ScanGoodsActivity.this).setView
                (root).setCancelable(false);
        final Dialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        root.findViewById(R.id.goto_agin).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        root.findViewById(R.id.cancel_action).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                showProgress();
                mPresenter.cancelTransaction();
            }
        });
    }

    private void showHandInputDialog(final int type) {
        View root = View.inflate(ScanGoodsActivity.this, R.layout.handinput_dialog, null);
        final AlertDialog.Builder builder = new AlertDialog.Builder(ScanGoodsActivity.this).setView(root)
                .setCancelable(false);
        TextView titleName = root.findViewById(R.id.title_name);
        ImageView img = root.findViewById(R.id.img);
        TextView done = root.findViewById(R.id.num_done);
        switch (type) {
            case IS_BARCODE:
                App.playSound(getResources().getString(R.string.sound_enter_bar_code));
                titleName.setText(R.string.dialog_title_hand_input);
                img.setImageDrawable(this.getResources().getDrawable(R.mipmap.input_icon_shangpin));
                done.setText(R.string.done);
                break;
            /*case IS_COUPON:
                titleName.setText("输入优惠券条码享受优惠");
                img.setImageDrawable(this.getResources().getDrawable(R.mipmap.input_icon_ticket));
                done.setText("确认");
                break;*/
            case IS_MEMBER:
                titleName.setText(R.string.dialog_title_vip);
                img.setImageDrawable(this.getResources().getDrawable(R.mipmap.input_icon_member));
                done.setText(R.string.login);
                break;
        }

        final Dialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        final EditText inputBarCode = (EditText) root.findViewById(R.id.input_bar_code);
        inputBarCode.setText("");
        root.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        root.findViewById(R.id.num_done).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                mCurrentBarCode = inputBarCode.getText().toString();
                if (TextUtils.isEmpty(mCurrentBarCode)) {
                    ToastUtils.toastShow("输入不能为空,请重试", ToastUtils.ERROR);
                    mCurrentBarCode = "";
                } else {
                    switch (type) {
                        case IS_BARCODE:
                            // 先获取下商品信息..确认商品是否合法..
                            //TODO 手动输码，先获取本地库中有没有有就使用商品库中的barcode
                            List<GoodsWeight> goodsWeightList = GoodsHelper.getLikeGoodsWeightByBarcode(App.getInstances().getDaoSession().getGoodsWeightDao(), mCurrentBarCode);
                            if(goodsWeightList != null && goodsWeightList.size() > 0){
                                mCurrentBarCode = goodsWeightList.get(0).getBarcode();
                            }
                            LogUtils.d("手动输商品码mCurrentBarCode:" + mCurrentBarCode, true);
                            mPresenter.getItemInfo(mCurrentBarCode, "1");
                            break;
                        /*case IS_COUPON:
                            // 先获取下优惠劵是否合法
                            mPresenter.getCouponInfo(mCurrentBarCode);
                            break;*/
                        case IS_MEMBER:
                            LogUtils.d("手动输会员卡mCurrentBarCode:" + mCurrentBarCode, true);
                            // 先获取下会员是否合法
                            mPresenter.getMemberInfo(mCurrentBarCode);
                            break;
                    }

                    mCurrentBarCode = "";
                }
            }
        });

        root.findViewById(R.id.num_delete).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mCurrentBarCode = "";
                inputBarCode.setText("");
            }
        });

        root.findViewById(R.id.num_0).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                appendTextView(inputBarCode, "0");
            }
        });

        root.findViewById(R.id.num_1).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                appendTextView(inputBarCode, "1");
            }
        });

        root.findViewById(R.id.num_2).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                appendTextView(inputBarCode, "2");
            }
        });

        root.findViewById(R.id.num_3).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                appendTextView(inputBarCode, "3");
            }
        });

        root.findViewById(R.id.num_4).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                appendTextView(inputBarCode, "4");
            }
        });

        root.findViewById(R.id.num_5).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                appendTextView(inputBarCode, "5");
            }
        });

        root.findViewById(R.id.num_6).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                appendTextView(inputBarCode, "6");
            }
        });

        root.findViewById(R.id.num_7).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                appendTextView(inputBarCode, "7");
            }
        });

        root.findViewById(R.id.num_8).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                appendTextView(inputBarCode, "8");
            }
        });

        root.findViewById(R.id.num_9).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                appendTextView(inputBarCode, "9");
            }
        });
    }

    private void appendTextView(EditText tv, String append) {
        String old = tv.getText().toString();
        old += append;
        tv.setText(old);
        tv.setSelection(old.length());
    }

    /*private void hideItemDialog() {
        if (mItemDialog != null && mItemDialog.isShowing()) {
            mItemDialog.dismiss();
            mItemDialog = null;
        }
        mItemDialogIsShow = false;
    }*/

   /* @Override
    public void showItemDialog(boolean isShowDialog, final SaleFlow saleFlow, final TradeHead tradeHead) {
        if(isShowDialog){
            hideItemDialog();
            mItemDialogIsShow = true;

            View root = View.inflate(ScanGoodsActivity.this, R.layout.item_dialog, null);
            ImageView img = root.findViewById(R.id.img);
            TextView item_name = (TextView) root.findViewById(R.id.item_name);
            TextView item_current_price = (TextView) root.findViewById(R.id.item_current_price);
            TextView item_origin_price = (TextView) root.findViewById(R.id.item_origin_price);
            item_origin_price.setPaintFlags(item_origin_price.getPaintFlags() | Paint
                    .STRIKE_THRU_TEXT_FLAG);
            ImageOptions imageOptions = new ImageOptions.Builder()
                    .setFadeIn(true)
                    .setLoadingDrawableId(R.mipmap.commodity)
                    .build();
            //todo 没有商品图片接口
            //x.image().bind(img, saleFlow.get(),imageOptions);

            if (saleFlow.getPrice() == saleFlow.getUnitprice()) {
                item_origin_price.setVisibility(View.GONE);
            } else {
                item_origin_price.setVisibility(View.VISIBLE);
            }

            item_name.setText(saleFlow.getFname());
            item_current_price.setText("¥" + Tools.fen2yuan(saleFlow.getPrice() + ""));
            item_origin_price.setText("原价: ¥" + Tools.fen2yuan(saleFlow.getUnitprice() + ""));

            AlertDialog.Builder builder = new AlertDialog.Builder(ScanGoodsActivity.this).setView(root)
                    .setCancelable(false);
            mItemDialog = builder.create();
            mItemDialog.setCanceledOnTouchOutside(false);
            mItemDialog.show();

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    hideItemDialog();
                }
            }, 1000);
        }
        processItemList(tradeHead);
    }*/

    @Override
    public void processItemList(TradeHead tradeHead) {
        updatePriceView(tradeHead);
        updateAdapter(mPresenter.getItemList());
    }

    @Override
    public void gotoPay() {

        TradeHead tradeHead = Means.getInstance().getRec_Tran();
        if (tradeHead.getDisc_amt() == 0) {
            LogUtils.d("没有优惠直接跳转到支付方式页面", false);
            Intent intent = new Intent(ScanGoodsActivity.this, PayWayActivity.class);
            startActivity(intent);
            finish();
            return;
        }
        View root = View.inflate(ScanGoodsActivity.this, R.layout.confirm_trade_dialog, null);
        TextView totalAmount = root.findViewById(R.id.total_amount);
        TextView mchCoupon = root.findViewById(R.id.mch_coupon);
        TextView price = root.findViewById(R.id.price_value);
        totalAmount.setText("¥" + Tools.getFormatNumber(tradeHead.getAmount() + tradeHead.getDisc_amt()));
        mchCoupon.setText("¥" + Tools.getFormatNumber(tradeHead.getDisc_amt()));
        String priceTxt = "实付金额：¥" + Tools.getFormatNumber(tradeHead.getAmount());
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(priceTxt);

        stringBuilder.setSpan(new AbsoluteSizeSpan(ScreenUtils.sp2px(ScanGoodsActivity.this, 20)), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        stringBuilder.setSpan(new ForegroundColorSpan(this.getResources().getColor(R.color.black)), 0, 5,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setText(stringBuilder);

        AlertDialog.Builder builder = new AlertDialog.Builder(ScanGoodsActivity.this, R.style.NoBackGroundDialog).setView(root)
                .setCancelable(false);
        final Dialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        root.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        root.findViewById(R.id.gotop).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent(ScanGoodsActivity.this, PayWayActivity.class);
                startActivity(intent);
                finish();
            }
        });
        dialog.show();

    }

    private void updatePriceView(TradeHead tradeHead) {
        mCurrentOrder = tradeHead;
        if (mCurrentOrder == null) {
            return;
        }
        //mMchCoupon.setText("-¥" + Tools.fen2yuan(mCurrentOrder.getDisc_amt() + ""));
        //mTotalAmount.setText("¥" + Tools.fen2yuan(mCurrentOrder.getAmount() + mCurrentOrder.getDisc_amt() + ""));
        double count = mCurrentOrder.getCount();
        String textStr = String.format(getResources().getString(R.string.total_goods_number),(int)count);
        SpannableStringBuilder builder = new SpannableStringBuilder(textStr);

        builder.setSpan(new AbsoluteSizeSpan(ScreenUtils.sp2px(ScanGoodsActivity.this, 23)), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(new ForegroundColorSpan(this.getResources().getColor(R.color.gray_color)), 0, 2,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(new AbsoluteSizeSpan(ScreenUtils.sp2px(ScanGoodsActivity.this, 23)), textStr.length() - 3, textStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(new ForegroundColorSpan(this.getResources().getColor(R.color.gray_color)), textStr.length() - 3, textStr.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTotalCount.setText(textStr);
        mPrice.setText("¥" + Tools.getFormatNumber(mCurrentOrder.getAmount()));
    }

    private void updateAdapter(List<SaleFlow> saleFlowList) {
        if (mAdapter == null) {
            mAdapter = new GoodsRecyclerViewAdapter(ScanGoodsActivity.this, saleFlowList);
            mAdapter.setCallBack(new GoodsRecyclerViewAdapter.CallBack() {
                @Override
                public void clickNumber(int pos) {
                    changeGoodsCount(pos);
                }
            });
            mRecyclerView.setAdapter(mAdapter);
            mRecyclerView.scrollToPosition(0);
            mAdapter.setOnItemListener(ScanGoodsActivity.this);
        } else {
            mAdapter.setData(saleFlowList);
            mRecyclerView.scrollToPosition(0);
        }
    }

    private void changeGoodsCount(int pos) {
        /*
        View root = View.inflate(ScanGoodsActivity.this, R.layout.change_goods_count_dialog, null);
        Button cancle = root.findViewById(R.id.cancel);
        Button change = root.findViewById(R.id.change);
        EditText changeEdt = root.findViewById(R.id.edt_count);
        AlertDialog.Builder builder = new AlertDialog.Builder(ScanGoodsActivity.this).setView(root)
                .setCancelable(false);
        final Dialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String changeNumber = changeEdt.getText().toString().trim();
                if(changeNumber == null){
                    ToastUtils.toastShow("请输入修改商品个数", ToastUtils.ERROR);
                    return;
                }
                int count = Means.getInstance().getItemHead().get(pos).getCount();
                int changeCount = Integer.getInteger(changeNumber);
                if(changeCount < 0){
                    ToastUtils.toastShow("非法输入", ToastUtils.ERROR);
                    return;
                }
                if(changeCount == 0){
                    //删除条目
                    dialog.dismiss();
                    showProgress();
                    mPresenter.removeItem(pos);
                }
                int tmpCount = changeCount - count;
                if(tmpCount > 0){
                    //增加商品
                    dialog.dismiss();
                    showProgress();
                    mPresenter.getItemInfo(mCurrentBarCode, "1");
                }else if(tmpCount < 0){
                    //减少shangp
                    dialog.dismiss();
                    showProgress();
                    mPresenter.reduceItem(pos, count - changeCount);

                }
            }
        });
        */
        mChangeGoodsDialog = new ChangeGoodsDialog(this);
        mChangeGoodsDialog.setCallBack(new ChangeGoodsDialog.CallBack() {
            @Override
            public void close(View view) {
                mChangeGoodsDialog.dismiss();
            }

            @Override
            public void done(int num) {
                int count = mPresenter.getItemList().get(pos).getCount();
                if(num == 0){
                    //删除条目
                    mChangeGoodsDialog.dismiss();
                    showProgress();
                    mPresenter.removeItem(pos);
                    return;
                }
                int tmpCount = num - count;
                if(tmpCount > 0){
                    //增加商品
                    mChangeGoodsDialog.dismiss();
                    showProgress();
                    mPresenter.getItemInfo(mPresenter.getItemList().get(pos).getBarcode(), tmpCount+"");
                }else if(tmpCount < 0){
                    //减少shangp
                    mChangeGoodsDialog.dismiss();
                    showProgress();
                    mPresenter.reduceItem(pos, count - num);

                }
            }
        });
        mChangeGoodsDialog.show();
    }

    @Override
    public void onItemDelete(final int position) {
        if(!blScaleEvent || !blScannerEvent){
            return;
        }
        if(mPresenter.getIsVerify() || mPresenter.getIsCancelling()) {
            return;
        }
            // 等待 + 禁止扫码
        showLoad();
        View root = View.inflate(ScanGoodsActivity.this, R.layout.delete_dialog, null);
        TextView itemName = root.findViewById(R.id.item_name);
        TextView itemPrice = root.findViewById(R.id.item_price);
        SaleFlow goodsItem = mPresenter.getItemList().get(position);
        if (goodsItem != null) {
            itemName.setText(""+goodsItem.getFname());
            itemPrice.setText("¥" + Tools.getFormatNumber(goodsItem.getPrice()));
        }

        //ImageOptions imageOptions = new ImageOptions.Builder()
        //        .setFadeIn(true)
        //        .setLoadingDrawableId(R.mipmap.commodity)
        //        .build();

        //x.image().bind(itemIcon, goodsItem.getGoods_img(),imageOptions);
        AlertDialog.Builder builder = new AlertDialog.Builder(ScanGoodsActivity.this).setView(root)
                .setCancelable(false);
        final Dialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        root.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                hideLoad();
            }
        });

        root.findViewById(R.id.done).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showProgress();
                mPresenter.removeItem(position);
                dialog.dismiss();
                hideLoad();
            }
        });
    }

    @Override
    public void onItemAdd(int position) {
        if(mPresenter.getIsVerify() || mPresenter.getIsCancelling()) {
            return;
        }
        showProgress();
        mPresenter.addItem(position);
    }

    @Override
    public void onItemMiuns(int position) {
        if(mPresenter.getIsVerify() || mPresenter.getIsCancelling()) {
            return;
        }
        showProgress();
        mPresenter.reduceItem(position);
    }

    //msg.what==1 根据msg.obj创建weightDlg
    //msg.what==2 根据msg.obj修改weightDlg显示内容
    //msg.what==3 人工干预了重量，关闭weightDlg
    //msg.what==4 重量符合，关闭weightDlg
    Handler weightHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //mWeight.setText("当前重量:" + String.valueOf(Means.weightqty) + "/预期总重量:" + Means.TotalWeight + "/购物袋重量:" + Means.BagWeight);
            LogUtils.d("msg.what" + msg.what, false);
            if(supervisorLoginDialog != null && supervisorLoginDialog.isShowing()){
//                weightTipsDialog.dismiss();
                return;
            }

            if (msg.what == 1) {
                if(weightTipsDialog != null && weightTipsDialog.isShowing()){

                }else {
                    if(weightTipsDialog == null) {
                        weightTipsDialog = new WeightTipsDialog(ScanGoodsActivity.this, msg.obj.toString(), "详细重量信息");
                        weightTipsDialog.setCallBack(new WeightTipsDialog.CallBack() {
                            @Override
                            public void adminClick(View view) {
//                                showSuperVisor(0, "", "");
                                showSuperLoginDialog();
                            }

                            @Override
                            public void helpClick(View view) {
                                LampUtil.LampAlarm(serialPortFunction, 0, 2, 0);
                                App.getSoundMgr().play("e4");
                            }
                        });
                        weightTipsDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialogInterface) {
                                LampUtil.LampAlarm(serialPortFunction, 0, 0, 0);
                            }
                        });
                    }
                    weightTipsDialog.show();
                }
                mPresenter.serWeighting(true);
            }
            else if(msg.what == 2){
                //更新重量提示内容
                if(weightTipsDialog != null && weightTipsDialog.isShowing()){
                    weightTipsDialog.setContent(msg.obj.toString());
                }else if(weightTipsDialog != null && !weightTipsDialog.isShowing()){
                    weightTipsDialog.show();
                    weightTipsDialog.setContent(msg.obj.toString());
                }
            }else if (msg.what == 3) {
                if(weightTipsDialog != null) {
                    weightTipsDialog.stopSound();
                    weightTipsDialog.dismiss();
                    mPresenter.serWeighting(false);
                }
                Means.TotalWeight = Means.weightqty;
            } else if(msg.what == 4){
                if(weightTipsDialog != null && weightTipsDialog.isShowing()) {
                    weightTipsDialog.stopSound();
                    weightTipsDialog.dismiss();
                    mPresenter.serWeighting(false);
                }
                Means.TotalWeight = Means.weightqty;
            }
        }
    };

    private void showSuperLoginDialog() {
        supervisorLoginDialog = new SuperVisorConfirmDialog(this);
        supervisorLoginDialog.setCallBack(new SuperVisorConfirmDialog.CallBack() {
            @Override
            public void close(View view) {
                supervisorLoginDialog.dismiss();
            }

            @Override
            public void done(String account, String psw) {
                supervisorLoginDialog.dismiss();
                ServiceInterface.getInstance().superVisor(account, psw, JLFConstant.SCO_WEIGHT_DIFF);
            }

            @Override
            public void finish(String account_psw) {
                if(TextUtils.isEmpty(account_psw) || !account_psw.contains("&")){
                    ToastUtils.toastShow("请扫描合法的管理员授权码", ToastUtils.ERROR);
                    return;
                }

                String date = account_psw.substring(0, account_psw.indexOf("&"));
                String account = account_psw.substring(account_psw.indexOf("&") + 1, account_psw.indexOf("-"));
                superVisor = account;
                String psw = account_psw.substring(account_psw.indexOf("-") + 1, account_psw.length());
                LogUtils.d("管理员账户：" + date + "_" + account + '_' + psw, false);
                supervisorLoginDialog.dismiss();
                if(!checkTimeLegal(date)){
                    ToastUtils.toastShow("二维码已过期", ToastUtils.ERROR);
                }else {
                    ServiceInterface.getInstance().superVisor(account, psw, JLFConstant.SCO_WEIGHT_DIFF);
                }
            }
        });
        supervisorLoginDialog.show();
    }

    /**
     * 隐藏等待框
     */
    @Override
    public void hideLoad() {
        blScannerEvent = true;
        blScaleEvent = true;
        //loadView.setVisibility(View.GONE);
    }
    /**
     * 显示等待窗
     */
    @Override
    public void showLoad() {
        blScaleEvent = false;
        blScannerEvent = false;
        //if (!loadView.isShown()) {
        //    loadView.setVisibility(View.VISIBLE);
       // }
    }

    @Override
    public void weight(String weight) {
        LogUtils.d("获取称重数据：" + weight, false);
        mPresenter.weight(weight);
    }


    private static class BarCodeHandler extends Handler {

        private final WeakReference<ScanGoodsActivity> mActivty;

        private BarCodeHandler(ScanGoodsActivity mActivty) {
            this.mActivty = new WeakReference<ScanGoodsActivity>(mActivty);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ScanGoodsActivity activity = mActivty.get();
            if (activity != null) {
                if (msg.what == MSG_BARCODE) {
                    BaseGoodsItem baseGoodsItem = (BaseGoodsItem) msg.obj;
                    activity.mPresenter.getItemInfo(baseGoodsItem.getBarcode(), baseGoodsItem.getQty());
                    LogUtils.d("handler send msg to service", true);
                }

            }
        }
    }

    private boolean checkTimeLegal(String time){
        boolean legal = false;
        long currentTime = new Date().getTime();

        long printTime = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        try {
            Date date = format.parse(time);
            printTime = date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        LogUtils.d("商品页判断管理员二维码过期时间:" + "currentTime:" + currentTime + "printTime:" + printTime, true);
        if(((currentTime - printTime) < (24* 3600000))){
            legal = true;
        }

        return legal;
    }


    @Override
    public void confirmGoods() {
        mPresenter.shutDownThread();
        weightTipsDialog.dismiss();
        Intent intent = new Intent(ScanGoodsActivity.this, SuperVisorConfirmGoodsActivity.class);
//        intent.putExtra("goodslist", (Serializable) mPresenter.getItemList());
        startActivityForResult(intent, CONFIRM_GOODS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        processItemList(Means.getInstance().getRec_Tran());
        LogUtils.e("干预页回到商品列表界面Means.TotalWeight" + Means.TotalWeight);
        LogUtils.e("干预页回到商品列表界面Means.weightqty" + Means.TotalWeight);

        mPresenter.processNor(superVisor);
        Means.blApproveWeight = true;
//        if(mPresenter.getIsCancelling()){
            Means.TotalWeight = Means.weightqty;
//        }
//
//        mPresenter.setIsVerify(false);
//        mPresenter.setIsCancelling(false);
//        hideLoad();
    }
}
